<template>
  <div class="app-container">
    <!-- 演示echarts -->
    <div style="display: flex; gap: 20px; align-items: flex-start; margin-bottom: 20px;">
      <!-- 切换显示按钮 -->
      <el-button type="primary" @click="toggleChart">切换图表</el-button>
      <!-- 为 ECharts 准备一个定义了宽高的 DOM -->
      <div id="main" style="width: 800px; height: 400px;" v-if="showMainChart"></div>
      <div id="main2" style="width: 800px; height: 400px;" v-if="!showMainChart"></div>
    </div>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="purposeTitle">
        <el-input
          v-model="queryParams.purposeTitle"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购单位" prop="subhead">
        <el-input
          v-model="queryParams.subhead"
          placeholder="请输入采购单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预算金额" prop="budget">
        <el-input
          v-model="queryParams.budget"
          placeholder="请输入预算金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购时间" prop="purposeTime">
        <el-date-picker clearable
                        v-model="queryParams.purposeTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择预计采购时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否投标" prop="isBid">
        <el-select v-model="queryParams.isBid" placeholder="请选择是否投标" clearable>
          <el-option
            v-for="dict in dict.type.is_bid"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>



    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purposeManager:purpose:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purposeManager:purpose:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['purposeManager:purpose:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purposeManager:purpose:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purposeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目id" align="center" prop="purposeId" />
      <el-table-column label="项目名称" align="center" prop="purposeTitle" />
      <el-table-column label="采购单位" align="center" prop="subhead" />
      <el-table-column label="预算金额" align="center" prop="budget" />
      <el-table-column label="采购需求情况" align="center" prop="content" />
      <el-table-column label="预计采购时间" align="center" prop="purposeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purposeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否投标" align="center" prop="isBid">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.is_bid" :value="scope.row.isBid"/>
        </template>
      </el-table-column>
      <el-table-column label="附件" align="center" prop="accessory" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purposeManager:purpose:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['purposeManager:purpose:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购意向对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="purposeTitle">
          <el-input v-model="form.purposeTitle" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="采购单位" prop="subhead">
          <el-input v-model="form.subhead" placeholder="请输入采购单位" />
        </el-form-item>
        <el-form-item label="预算金额" prop="budget">
          <el-input v-model="form.budget" placeholder="请输入预算金额" />
        </el-form-item>
        <el-form-item label="采购需求情况">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="预计采购时间" prop="purposeTime">
          <el-date-picker clearable
                          v-model="form.purposeTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择预计采购时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否投标" prop="isBid">
          <el-select v-model="form.isBid" placeholder="请选择是否投标">
            <el-option
              v-for="dict in dict.type.is_bid"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="附件" prop="accessory">
          <el-input v-model="form.accessory" placeholder="请输入附件" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>

import {listPurpose,getPurpose,addPurpose,updatePurpose,delPurpose} from "@/api/kobe/manager/purposes/purpose";
import * as echarts from 'echarts';
export default {
  name: "Purpose",
  dicts: ['is_bid'],
  data() {
    return {
      showMainChart: true,//是否显示主图表
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购意向表格数据
      purposeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purposeTitle: null,
        subhead: null,
        budget: null,
        purposeTime: null,
        isBid: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()

  },
  mounted(){

    this.initChart();
    this.initChart2();
  },
  methods: {

    initChart2() {

      var chartDom = document.getElementById('main2');
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        legend: {
          top: 'bottom'
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        series: [
          {
            name: 'Nightingale Chart',
            type: 'pie',
            radius: [50, 250],
            center: ['50%', '50%'],
            roseType: 'area',
            itemStyle: {
              borderRadius: 8
            },
            data: []
          }
        ]
      };

      option && myChart.setOption(option);

      listPurpose().then(res=>{//获取数据

        // 构造饼图所需的数据格式
        const pieData = res.rows.map(item => ({
          name: item.subhead,
          value: parseFloat(item.budget) || 0
        }));

        //更新
        myChart.setOption({

          series: [
            {
              data: pieData

            }
          ]
        })

      })
      ;


    },

    initChart() {
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById('main'));

      // 指定图表的配置项和数据
      var option = {
        title: {//标题
          text: '采购预算金额'
        },
        tooltip: {//提示

        },
        legend: {//图例
          data: ['金额']
        },
        xAxis: {//横轴
          data: []
        },
        yAxis: {//纵轴

        },
        series: [//数据系列
          {
            name: '单位/元',
            type: 'bar',
            data: []
          }
        ]
      };

      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);//绘制图表


      listPurpose().then(res=>{//获取数据
        const subheadData=res.rows.map(item=>item.subhead);
        const budgetData=res.rows.map(item=>item.budget);


        //更新
        myChart.setOption({
          xAxis: {
            data: subheadData
          },
          series: [
            {
              data: budgetData
            }
          ]
        })

      })
      ;

    },
    /** 查询采购意向列表 */
    getList() {
      this.loading = true
      listPurpose(this.queryParams).then(response => {
        this.purposeList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        purposeId: null,
        purposeTitle: null,
        subhead: null,
        budget: null,
        content: null,
        purposeTime: null,
        isBid: null,
        accessory: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purposeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加采购意向"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const purposeId = row.purposeId || this.ids
      getPurpose(purposeId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改采购意向"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.purposeId != null) {
            updatePurpose(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPurpose(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purposeIds = row.purposeId || this.ids
      this.$modal.confirm('是否确认删除采购意向编号为"' + purposeIds + '"的数据项？').then(function() {
        return delPurpose(purposeIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    // 切换图表显示状态
    toggleChart() {
      // 切换状态（true→false，false→true）
      this.showMainChart = !this.showMainChart;
      // 可选：切换后重新渲染图表（避免隐藏时尺寸异常）
      this.$nextTick(() => {//延迟执行，确保图表容器已渲染
        if (this.showMainChart) {
          this.initChart(); // 重新初始化main图表
        } else {
          this.initChart2(); // 重新初始化main2图表
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purposeManager/purpose/export', {
        ...this.queryParams
      }, `purpose_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

/* 搜索区域优化 - 更精致的卡片感 */
.el-form--inline {
  background: #fff;
  padding: 16px 20px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  transition: box-shadow 0.3s ease;
}

.el-form--inline:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-right: 20px !important;
  margin-bottom: 12px !important;
}

.el-form-item__label {
  color: #4e5969 !important;
  font-size: 13px;
  padding-right: 8px !important;
}

/* 按钮组优化 - 强调主次关系 */
.el-row.mb8 {
  margin-bottom: 16px !important;
  display: flex;
  align-items: center;
  gap: 8px;
}

.el-button {
  border-radius: 6px;
  font-size: 13px;
  padding: 6px 15px;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.el-button--primary {
  background-color: #165dff;
  border-color: #165dff;
}

.el-button--primary:hover {
  background-color: #0e42d2;
  border-color: #0e42d2;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(22, 93, 255, 0.3);
}

.el-button--plain {
  border-color: #e5e6eb;
  color: #4e5969;
}

.el-button--plain:hover {
  background-color: #f2f3f5;
  border-color: #dcdfe6;
}

/* 表格样式 - 增强可读性和层次感 */
.el-table {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: none !important;
  overflow: hidden;
}

.el-table::before {
  display: none; /* 去除底部边框线 */
}

.el-table th {
  background-color: #f7f8fa !important;
  color: #4e5969 !important;
  font-weight: 500 !important;
  height: 50px !important;
  padding: 0 16px !important;
  border-bottom: 1px solid #f0f2f5 !important;
}

.el-table td {
  height: 48px !important;
  padding: 0 16px !important;
  border-bottom: 1px solid #f0f2f5 !important;
}

/* 表格行交互效果 */
.el-table tr {
  transition: background-color 0.2s ease;
}

.el-table tr:hover > td {
  background-color: #f7faff !important;
}

.el-table__row--current > td {
  background-color: #e8f3ff !important;
}

/* 操作列按钮 - 图标与文字对齐 */
.el-table .el-button--text {
  color: #165dff;
  padding: 4px 8px;
  margin: 0 2px;
  border-radius: 4px;
  font-size: 12px;
}

.el-table .el-button--text:hover {
  color: #0e42d2;
  background-color: #f0f7ff;
}

/* 分页控件 - 与表格视觉统一 */
.pagination {
  margin-top: 16px;
  padding: 12px 0;
  text-align: right;
}

.el-pagination__item {
  border-radius: 4px;
}

.el-pagination__item.active {
  background-color: #165dff;
  border-color: #165dff;
}

/* 对话框 - 精致弹窗效果 */
.el-dialog {
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.el-dialog__header {
  padding: 18px 24px;
  background-color: #f7f8fa;
  border-bottom: 1px solid #f0f2f5;
}

.el-dialog__title {
  color: #1d2129;
  font-size: 16px;
  font-weight: 500;
}

.el-dialog__body {
  padding: 24px;
  max-height: 70vh;
  overflow-y: auto;
}

.el-dialog__footer {
  padding: 16px 24px;
  border-top: 1px solid #f0f2f5;
  background-color: #fff;
}

/* 表单元素 - 精致输入体验 */
.el-input__inner, .el-select__inner, .el-textarea__inner {
  border-radius: 6px;
  border-color: #dcdfe6;
  height: 38px;
  padding: 0 12px;
  font-size: 13px;
  transition: all 0.2s ease;
}

.el-input__inner:focus, .el-select__input:focus, .el-textarea__inner:focus {
  border-color: #165dff;
  box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.2);
  outline: none;
}

.el-date-picker {
  border-radius: 6px;
}

/* 字典标签 - 更和谐的色彩 */
.dict-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

/* 富文本编辑器 */
.editor {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  min-height: 192px;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .el-form-item {
    margin-right: 12px !important;
  }
}

@media (max-width: 768px) {
  .app-container {
    padding: 12px;
  }

  .el-form--inline {
    padding: 12px;
  }

  .el-form-item {
    width: 100% !important;
    margin-right: 0 !important;
  }

  .el-row.mb8 {
    flex-wrap: wrap;
  }

  .el-col {
    flex: 1 0 auto;
    min-width: 80px;
  }

  .el-dialog {
    width: 90% !important;
  }
}
</style>
